package de.imdb250junkie.gui;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import de.imdb250junkie.locale.LocaleUtils;
import de.imdb250junkie.utils.Loader;

public class LanguageSelector extends JDialog implements ActionListener
{

    /**
     * genrated UID.
     */
    private static final long serialVersionUID = 4055017718701214076L;
    /**
     * Buttons
     */
    private final transient JButton okButton, cancelButton;

    /**
     * combo box
     */
    private final transient JComboBox<Locale> selector;

    /**
     * 
     * @param owner
     *            the owner of this dialog
     */
    public LanguageSelector(final Frame owner)
    {
        super(owner, true);

        final ResourceBundle locale = ResourceBundle.getBundle(
                "de.imdb250junkie.locale.GUIStrings", LocaleUtils.getLocale());
        okButton = new JButton(locale.getString("ok"));
        okButton.addActionListener(this);
        okButton.setSize(80, 30);
        cancelButton = new JButton(locale.getString("cancel"));
        cancelButton.addActionListener(this);
        cancelButton.setSize(80, 30);
        selector = new JComboBox<>((Locale[]) LocaleUtils.getAvailableLocales()
                .toArray());
        selector.setSize(190, 30);

        this.setResizable(false);
        this.setModal(true);
        this.setBounds(owner.getBounds());
        this.setSize(new Dimension(200, 100));
        this.setLayout(new GridLayout(2, 1));

        final JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER, 10,
                10));
        buttons.add(okButton);
        buttons.add(cancelButton);

        this.add(selector);
        this.add(buttons);

        this.setVisible(true);
    }

    @Override
    public void actionPerformed(final ActionEvent event)
    {
        if (event.getSource() == okButton)
        {
            LocaleUtils.setLocale((Locale) selector.getSelectedItem());
            this.dispose();
            super.getOwner().dispose();
            Loader.load();
            JOptionPane.showMessageDialog(
                    this,
                    ResourceBundle.getBundle(
                            "de.imdb250junkie.locale.GUIStrings",
                            LocaleUtils.getLocale()).getString("update_hint"),
                    "DB-Update", JOptionPane.INFORMATION_MESSAGE);
        }
        else if (event.getSource() == cancelButton)
        {
            this.dispose();
        }

    }
}